package com.highcom.controller;

import com.highcom.config.RedisConfig;
import com.highcom.constant.MessageConstant;
import com.highcom.constant.RedisMessageConstant;
import com.highcom.entity.Result;
import com.highcom.model.Order;
import com.highcom.service.OrderService;
import com.highcom.utils.SMSUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Map;

/**
 * @version 1.0
 * @Author YangJiaQuan_hrbnu
 * @Date 2024/8/7 9:37
 */

@RestController
@RequestMapping("/order")
public class OrderController {
    private static JedisPool jedisPool;
    @Autowired
    private RedisConfig redisConfig;
    @PostConstruct
    public void init(){
        jedisPool = redisConfig.redisPoolFactory();
    }
    @Resource
    private OrderService orderService;


    @RequestMapping("/submit")   //逻辑分析：获取redis中的验证码与用户填写的验证码，进行比对，比对正确则成功预约发送短信
    public Result submit(@RequestBody Map map){
        String telephone = (String) map.get("telephone");
        String validateCode = (String) map.get("validateCode");
        //  redis获取
        String validateCodeByRedis = jedisPool.getResource().get(telephone+ RedisMessageConstant.SENDTYPE_ORDER);
        //  比对
        if(validateCode!=null && validateCodeByRedis!=null && validateCode.equals(validateCodeByRedis)){
            map.put("orderType", Order.ORDERTYPE_WEIXIN); // 微信？电话
            Result result = null;
            try{
                result = orderService.order(map);
            } catch (Exception e){
                e.printStackTrace();
                return result;
            }
            // 预约成功发送短信
            if(result.isFlag()){
                try{
                    SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE,telephone,"0000");
                } catch (Exception e){
                    e.printStackTrace();
                }
            }
            return result;
        }else{
            return new Result(false,MessageConstant.VALIDATECODE_ERROR);
        }
    }

    @RequestMapping("/findById")
    public Result findById(Integer id){
        try{
            Map map = orderService.findById(id);
            return new Result(true,MessageConstant.QUERY_ORDER_SUCCESS,map);
        } catch (Exception e){
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_ORDER_FAIL);
        }


    }

}
